import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { ApiService } from '@srvs/api.service';
import { NzNotificationService } from 'ng-zorro-antd';

@Component({
  selector: 'edit-company',
  templateUrl: './edit-company.component.html',
  styles: [`
    :host ::ng-deep .form-inner {
      padding: 16px 40px 0;
    }
    :host ::ng-deep .label-width {
      width: 110px;
    }
  `]
})
export class EditCompanyComponent implements OnInit {

  public validateForm: FormGroup;
  public companyTypes: any[] = [];

  @Input() public data: any;

  constructor(
    private formBuilder: FormBuilder,
    private apiSrv: ApiService,
    private msgSrv: NzNotificationService
  ) {
    this.load();
  }

  public ngOnInit(): void {
    const data: any = this.data || {};

    this.validateForm = this.formBuilder.group({
      companyNameChs: [data.companyNameChs || null, [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      companyNameEng: [data.companyNameEng || null, [Validators.required, Validators.minLength(2), Validators.maxLength(50)]],
      companyCode: [data.companyCode || null, [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      companyType: [data.companyType || null, [Validators.required]],
      alias: [data.alias || null, [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      isValid: [typeof data.isValid === 'boolean' ? data.isValid : null, [Validators.required]]
    });
  }

  public load(): void {
    const apiCompanyTypes: string = `/api/base-type-keys/companyType/base-type-values`;
    this.apiSrv.get(apiCompanyTypes).subscribe(
      data => {
        if (Array.isArray(data)) this.companyTypes = data;
      },
      error => this.msgSrv.error('公司类型加载失败！', error.message)
    );
  }

  public hasError(controlName: string): boolean {
    return !!(
      this.validateForm.get(controlName).dirty &&
      this.validateForm.get(controlName).errors
    );
  }

  public submit(): Observable<any> {
    for (const item in this.validateForm.controls) {
      this.validateForm.controls[item].markAsDirty();
      this.validateForm.controls[item].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      const apiCompanies: string = '/api/companies';
      let body: any = Object.assign({}, this.validateForm.value);

      if (this.data) {
        body.id = this.data.id;
        return this.apiSrv.put(apiCompanies, body);
      } else {
        return this.apiSrv.post(apiCompanies, body);
      }

    } else {
      return new Observable(observer => observer.complete());
    }
  }

}
